package shopping.web;

import shopping.bean.Admin;
import shopping.service.AdminService;
import shopping.service.impl.AdminServiceImpl;
import shopping.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class AdminServlet extends BaseServlet{
    private AdminService adminService = new AdminServiceImpl();

    /**
     * 处理登录的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //  1、获取请求的参数
//        String adminname = req.getParameter("adminname");
//        String password = req.getParameter("password");
        // 调用 adminService.login()登录处理业务
//        Admin admin = new Admin();
//        System.out.println("注入之前：" + Admin);
        Admin admin = WebUtils.copyParamToBean(req.getParameterMap(), new Admin());
//        try {
//            BeanUtils.populate(admin,req.getParameterMap());
//            System.out.println("注入之后：" + admin);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
        Admin loginAdmin = adminService.login(new Admin(null, admin.getAdminname(), admin.getPassword(), null));
        // 如果等于null,说明登录 失败!
        if (loginAdmin == null) {
            // 把错误信息，和回显的表单项信息，保存到Request域中
            req.setAttribute("msg", "用户或密码错误！");
            req.setAttribute("adminname", admin.getAdminname());
            //   跳回登录页面
            req.getRequestDispatcher("/view/admin/login.jsp").forward(req, resp);
        } else {
            // 登录 成功
            //跳到成功页面login_success.html
            req.getSession().setAttribute("admin",loginAdmin);
            req.getRequestDispatcher("/view/admin/login_success.jsp").forward(req, resp);
        }

    }

    /**
     * 处理注册的功能
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取Session中的验证码
        String attribute = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);


        //  1、获取请求的参数
//        String Adminname = req.getParameter("Adminname");
//        String password = req.getParameter("password");
//        String email = req.getParameter("email");
        String code = req.getParameter("code");

        Admin admin = WebUtils.copyParamToBean(req.getParameterMap(), new Admin());

//        2、检查 验证码是否正确  === 写死,要求验证码为:abcde
        if (attribute != null && attribute.equalsIgnoreCase(code)) {
//        3、检查 用户名是否可用
            if (adminService.existsAdminname(admin.getAdminname())) {
                System.out.println("用户名[" + admin.getAdminname() + "]已存在!");

                // 把回显信息，保存到Request域中
                req.setAttribute("msg", "用户名已存在！！");
                req.setAttribute("adminname", admin.getAdminname());
                req.setAttribute("email", admin.getEmail());

//        跳回注册页面
                req.getRequestDispatcher("/view/admin/regist.jsp").forward(req, resp);
            } else {
                //      可用
//                调用Sservice保存到数据库
                adminService.registAdmin(new Admin(null,admin.getAdminname(), admin.getPassword(), admin.getEmail()));
//
//        跳到注册成功页面 regist_success.jsp
                req.getRequestDispatcher("/view/admin/regist_success.jsp").forward(req, resp);
            }
        } else {
            // 把回显信息，保存到Request域中
            req.setAttribute("msg", "验证码错误！！");
            req.setAttribute("adminname", admin.getAdminname());
            req.setAttribute("email", admin.getEmail());

            System.out.println("验证码[" + code + "]错误");
            req.getRequestDispatcher("/view/admin/regist.jsp").forward(req, resp);
        }

    }

    /**
     * 注销功能
     * @param req
     * @param resp
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp){

        //销毁Session中的用户登录信息，
        req.getSession().invalidate();
        //重定向到首页
        try {
            resp.sendRedirect("/view/admin/login.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
